package cn.com.zsw.gblog.config.scheduleTask;

import cn.com.zsw.gblog.config.cache.RedisCache;
import cn.com.zsw.gblog.constants.SysConstants;
import cn.com.zsw.gblog.modules.gblog.entity.GbPostsEntity;
import cn.com.zsw.gblog.modules.gblog.service.GbPostsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ：shiwangzhou
 * @Date ：Created in 2020-07-15 18:21
 * @Description： redis同步数据到MySQL中的定时任务。
 */
@Component
@Slf4j
public class RedisSyncTask {
    @Resource
    RedisCache redisCache;
    @Resource
    private GbPostsService postsService;

    /**
     * @Author: shiwangZhou
     * @Description: redis同步数据到MySQL中的定时任务。
     * @Date: 2020-07-15 18:22
     * @Return void
     * @Param
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void sync() {
        log.info("执行定时任务");
        //获取redis数据更新到数据库
        Map<String, Object> cacheMap = redisCache.getCacheMap(SysConstants.POST_VIEW_KEY);
        if (cacheMap == null || cacheMap.size() == 0) {
            return;
        }
        List<GbPostsEntity> list = new ArrayList<>();
        for (String postId : cacheMap.keySet()) {
            Integer count = (Integer) cacheMap.get(postId);
            GbPostsEntity gbPosts = this.postsService.getById(postId);
            if (gbPosts != null) {
                gbPosts.setViewsCount(count);
                list.add(gbPosts);
            }
        }
        postsService.updateBatchById(list);
        //删除缓存,
        redisCache.deleteObject(SysConstants.POST_VIEW_KEY);
        //从数据库获取数据更新缓存
        Map<String, Object> collect = postsService.list().stream()
                .collect(Collectors.toMap(gbPostsEntity -> gbPostsEntity.getId().toString(), GbPostsEntity::getViewsCount));
        redisCache.setCacheMap(SysConstants.POST_VIEW_KEY,collect);

    }
}
